package authoritah.ui.member.popup;

import java.awt.BorderLayout;
import java.awt.GridLayout;

import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SpringLayout;

import authoritah.db.Member;
import authoritah.utils.SpringUtilities;


public class MemberPopupView extends JDialog {

	private MemberPopupModel model;
	
	private JTextField name;
	private JTextField initialPoints;
	private JComboBox status;
	
	private JPanel mainPanel;
	private JPanel buttonPanel;
	private JButton save;

	public MemberPopupView(MemberPopupModel model) {
		this.model = model;
		setModal(true);
		
		initComponents(model);
		layoutComponents();
	}
	
	public MemberPopupView(MemberPopupModel model, Member member) {
		this.model = model;
		setModal(true);
		
		initComponents(model, member);
		layoutComponents();
	}	
	
	private void initComponents(MemberPopupModel model, Member member) {
		name = new JTextField(member.getName(), 20);
		model.setName(name.getDocument());
		
		initialPoints = new JTextField(Integer.toString(member.getInitialPoints()), 4);
		model.setInitialPoints(initialPoints.getDocument());
		
		status = new JComboBox(new Object[]{"Normal", "Dormant", "Trial", "Retrial"});
		status.setSelectedIndex(member.getStatus());
		model.setStatus(status.getModel());
		
		mainPanel = new JPanel(new SpringLayout());
		buttonPanel = new JPanel(new GridLayout(1,2));
		
		save = new JButton("Save");
	}
	
	private void initComponents(MemberPopupModel model) {
		name = new JTextField(20);
		model.setName(name.getDocument());
		
		initialPoints = new JTextField(4);
		model.setInitialPoints(initialPoints.getDocument());
		
		status = new JComboBox(new Object[]{"Normal", "Dormant", "Trial", "Retrial"});
		model.setStatus(status.getModel());
		
		mainPanel = new JPanel(new SpringLayout());
		buttonPanel = new JPanel(new GridLayout(1,2));
		
		save = new JButton("Save");
	}
	
	private void layoutComponents() {
		mainPanel.setBorder(BorderFactory.createTitledBorder("Create/Edit Member"));
		
		mainPanel.add(new JLabel("Name"));
		mainPanel.add(name);
		mainPanel.add(new JLabel("Initial Points"));
		mainPanel.add(initialPoints);
		mainPanel.add(new JLabel("Status"));
		mainPanel.add(status);
		
		SpringUtilities.makeCompactGrid(mainPanel, 1, 6, 0, 0, 4, 4);
		
		buttonPanel.add(save);
		
		this.getContentPane().setLayout(new BorderLayout());
		this.getContentPane().add(mainPanel, BorderLayout.CENTER);
		this.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
		
		this.pack();
	}
	
	public void setSaveAction(Action a) {
		save.setAction(a);
	}
}
